<template>
  <div id="app" :class="appClasses">
    <router-view v-slot="{ Component, route }">
      <transition
        :name="transitionName"
        mode="out-in"
        @before-enter="onBeforeEnter"
        @after-enter="onAfterEnter"
      >
        <keep-alive :include="cachedViews">
          <component :is="Component" :key="route.fullPath" />
        </keep-alive>
      </transition>
    </router-view>
    
    <!-- 全局加载遮罩 -->
    <transition name="fade">
      <div v-if="appStore.loading" class="global-loading">
        <div class="loading-content">
          <div class="loading-spinner"></div>
          <div class="loading-text">{{ appStore.loadingText || '加载中...' }}</div>
        </div>
      </div>
    </transition>
    
    <!-- 网络状态提示 -->
    <transition name="slide-down">
      <div v-if="!isOnline" class="network-status">
        <el-icon><WifiOff /></el-icon>
        <span>网络连接已断开，请检查网络设置</span>
      </div>
    </transition>
    
    <!-- 版本更新提示 -->
    <el-dialog
      v-model="showUpdateDialog"
      title="发现新版本"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="update-content">
        <el-icon class="update-icon"><Refresh /></el-icon>
        <p>检测到新版本，建议立即更新以获得更好的体验。</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleUpdateLater">稍后更新</el-button>
          <el-button type="primary" @click="handleUpdateNow">立即更新</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { WifiOff, Refresh } from '@element-plus/icons-vue'
import { useAppStore } from '@/store/app'
import { useUserStore } from '@/store/user'
import { useOnline } from '@vueuse/core'

const router = useRouter()
const route = useRoute()
const appStore = useAppStore()
const userStore = useUserStore()

// 网络状态
const isOnline = useOnline()

// 版本更新
const showUpdateDialog = ref(false)

// 应用样式类
const appClasses = computed(() => {
  return {
    'app-dark': appStore.isDark,
    'app-mobile': appStore.isMobile,
    'app-loading': appStore.loading
  }
})

// 页面过渡动画名称
const transitionName = computed(() => {
  if (appStore.isMobile) {
    return 'slide'
  }
  return 'fade'
})

// 缓存的视图
const cachedViews = computed(() => {
  return appStore.cachedViews
})

// 过渡动画事件
const onBeforeEnter = () => {
  appStore.setPageLoading(true)
}

const onAfterEnter = () => {
  appStore.setPageLoading(false)
}

// 处理版本更新
const handleUpdateNow = () => {
  showUpdateDialog.value = false
  window.location.reload()
}

const handleUpdateLater = () => {
  showUpdateDialog.value = false
  // 30分钟后再次提醒
  setTimeout(() => {
    showUpdateDialog.value = true
  }, 30 * 60 * 1000)
}

// 检查版本更新
const checkForUpdates = async () => {
  try {
    // 这里可以实现版本检查逻辑
    // const response = await api.checkVersion()
    // if (response.hasUpdate) {
    //   showUpdateDialog.value = true
    // }
  } catch (error) {
    console.error('检查版本更新失败:', error)
  }
}

// 监听网络状态变化
watch(isOnline, (online) => {
  if (online) {
    ElMessage.success('网络连接已恢复')
    // 重新获取数据
    appStore.refreshData()
  } else {
    ElMessage.warning('网络连接已断开')
  }
})

// 监听路由变化
watch(
  () => route.path,
  (newPath, oldPath) => {
    // 更新面包屑
    appStore.updateBreadcrumb(route)
    
    // 添加到访问历史
    appStore.addVisitedView(route)
    
    // 页面埋点
    if (import.meta.env.PROD) {
      // 这里可以添加页面访问统计
      console.log('页面访问:', newPath)
    }
  },
  { immediate: true }
)

// 全局键盘快捷键
const handleKeydown = (event) => {
  // Ctrl/Cmd + K 打开搜索
  if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
    event.preventDefault()
    appStore.toggleSearch()
  }
  
  // Ctrl/Cmd + / 打开帮助
  if ((event.ctrlKey || event.metaKey) && event.key === '/') {
    event.preventDefault()
    appStore.toggleHelp()
  }
  
  // ESC 关闭模态框
  if (event.key === 'Escape') {
    appStore.closeAllModals()
  }
}

// 全局错误处理
const handleError = (error) => {
  console.error('全局错误:', error)
  ElMessage.error('系统出现错误，请稍后重试')
}

// 全局未处理的Promise拒绝
const handleUnhandledRejection = (event) => {
  console.error('未处理的Promise拒绝:', event.reason)
  ElMessage.error('网络请求失败，请检查网络连接')
}

// 页面可见性变化
const handleVisibilityChange = () => {
  if (document.hidden) {
    // 页面隐藏时暂停一些操作
    appStore.pauseOperations()
  } else {
    // 页面显示时恢复操作
    appStore.resumeOperations()
    // 检查登录状态
    userStore.checkLoginStatus()
  }
}

// 组件挂载
onMounted(async () => {
  // 初始化应用
  await appStore.initApp()
  
  // 检查登录状态
  await userStore.checkLoginStatus()
  
  // 检查版本更新
  await checkForUpdates()
  
  // 添加事件监听
  document.addEventListener('keydown', handleKeydown)
  window.addEventListener('error', handleError)
  window.addEventListener('unhandledrejection', handleUnhandledRejection)
  document.addEventListener('visibilitychange', handleVisibilityChange)
  
  // 设置定时任务
  // 每30分钟检查一次版本更新
  setInterval(checkForUpdates, 30 * 60 * 1000)
  
  console.log('🎉 学生端应用已启动')
})

// 组件卸载
onUnmounted(() => {
  // 移除事件监听
  document.removeEventListener('keydown', handleKeydown)
  window.removeEventListener('error', handleError)
  window.removeEventListener('unhandledrejection', handleUnhandledRejection)
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})
</script>

<style lang="scss">
// 全局样式
#app {
  height: 100vh;
  overflow: hidden;
  
  &.app-loading {
    pointer-events: none;
  }
}

// 页面过渡动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}

.slide-enter-from {
  transform: translateX(100%);
}

.slide-leave-to {
  transform: translateX(-100%);
}

// 全局加载遮罩
.global-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .loading-content {
    text-align: center;
    color: var(--primary-color);
  }
  
  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid var(--el-border-color-light);
    border-top: 3px solid var(--primary-color);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 16px;
  }
  
  .loading-text {
    font-size: var(--font-size-base);
    font-weight: 500;
  }
}

// 网络状态提示
.network-status {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: var(--warning-color);
  color: white;
  padding: var(--spacing-3) var(--spacing-4);
  text-align: center;
  font-size: var(--font-size-sm);
  z-index: 9998;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-2);
}

// 版本更新对话框
.update-content {
  text-align: center;
  padding: var(--spacing-4) 0;
  
  .update-icon {
    font-size: 48px;
    color: var(--primary-color);
    margin-bottom: var(--spacing-4);
  }
  
  p {
    color: var(--el-text-color-regular);
    line-height: var(--line-height-relaxed);
  }
}

// 过渡动画
.slide-down-enter-active,
.slide-down-leave-active {
  transition: transform 0.3s ease;
}

.slide-down-enter-from,
.slide-down-leave-to {
  transform: translateY(-100%);
}

// 旋转动画
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

// 暗色主题适配
.app-dark {
  .global-loading {
    background: rgba(0, 0, 0, 0.9);
    color: white;
    
    .loading-spinner {
      border-color: var(--el-border-color-dark);
      border-top-color: var(--primary-color);
    }
  }
}

// 移动端适配
.app-mobile {
  .global-loading {
    .loading-content {
      padding: var(--spacing-4);
    }
  }
  
  .network-status {
    font-size: var(--font-size-xs);
    padding: var(--spacing-2) var(--spacing-3);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .update-content {
    .update-icon {
      font-size: 36px;
    }
  }
}
</style>